# -*- coding: utf-8 -*-
# @Time    : 2018/2/8 23:00
# @Author  : Soft
# @File    : controller.py
# @Desc    : 签到记录控制器
from flask import request, jsonify, render_template, redirect, send_file

from module.ExeclUtils.RecordExcel import getRecordExecl
from module.TimeUtils import *
from module.AuthUtil import auth_required
from module.admin import ad_login
from module.record import record
from module.record.service import ReService
from module.user.controller import u_login
from module.class_.service import ClzService
from module.cache import cache
from config import Check, Img, CHECK_AUTH

# 请假和签到接口 必须是已经登录的用户
from module.user.service import StuService


@record.route('/check_in/<kid>', methods=['post', 'get'])
@u_login.required
def check_in(kid):
    """
    学生签到 数据：课程id kid 签到状态：status
    :return:
    """
    if request.method == 'POST':
        tl = request.args.get('tl')
        tp = request.args.get('type')
        flag = request.form.get('flag')  # 标记 该标记用于规定可以免验证签到
        uid = u_login.get_user_id()
        if not ReService.is_has(kid=kid, sid=uid)[0]:
            if (tp and tp == 'qj') or (tl and tl == cache.get(Img.C_AUTH)) or (flag and flag == CHECK_AUTH):
                is_k = ClzService.is_has(kid)
                if kid and is_k[0]:
                    if tp and tp == 'qj':
                        rd_status = Check.QJ
                    else:
                        rd_status = check_limit(is_k[1].get('k_time'))
                    if isinstance(rd_status, int):
                        print('#####################################')
                        print(flag)
                        print(rd_status)
                        print('#####################################')

                        rd_time = get_time()
                        dt = float(request.form.get("dt", "0.0"))  # 2018 4 15  位置偏差
                        if ReService.add(k_id=kid, stu_id=uid, rd_time=rd_time, rd_status=rd_status, deviation=dt):
                            if rd_status == Check.CQ or rd_status == Check.CD:
                                ClzService.add_stu_num(kid=kid)  # 添加课程签到数
                            return jsonify(status=True, msg='签到或请假成功')
                        return jsonify(status=False, msg='签到系统异常')
                    return jsonify(status=False, msg='本节课签到未开始')
                return jsonify(status=False, msg='课程不存在')
            return jsonify(status=False, msg='失效的链接')
        return jsonify(status=False, msg='无需重复操作')
    elif request.method == 'GET':
        url = request.host_url[:-1] + request.full_path
        # print url
        prev = None
        flag = request.args.get('flag')
        ip = request.host
        print('#####################################')
        print(flag)
        print(ip)
        print(url)
        print('#####################################')

        if flag and flag == ip:
            prev = CHECK_AUTH
        print(prev)
        return render('get_check.html', data=dict(url=url, prev=prev, local=cache.get("local")))


@record.route('/delete/<rid>', methods=['post'])
@auth_required
def delete(rid):
    if rid:
        if ReService.remove(rid):
            return jsonify(status=True, msg='删除成功')
    return jsonify(status=False, msg='添加失败')


@record.route('/change', methods=['post'])
@auth_required
def change():
    forms = request.form.to_dict()
    rid = forms.pop('id')
    if rid:
        if ReService.change(rid=rid, **forms):
            return jsonify(status=True, msg='修改成功')
    return jsonify(status=False, msg='修改失败')


# 统计当前未签到的学员
@record.route('/count/<kid>', methods=['post'])
@auth_required
def count(kid):
    year = request.form.get('year', '2018')
    students = list(StuService.by_year(year))
    students.pop(0)
    no_check = list()
    if kid and int(kid) > 0:
        for stu in students:
            sid = int(stu.get('id'))
            if not ReService.is_has(kid=kid, sid=sid)[0]:
                no_check.append(stu)
        return jsonify(status=True, result=no_check)
    return jsonify(status=False, msg=u'没有选择课程')


@record.route('/query', methods=['post'])
@auth_required
def query():
    """
    获取签到记录 status 3.12 添加 记录状态 默认全部
    :return:
    """
    page = int(request.form.get('page', '1'))
    year = request.form.get('year', '')
    kid = request.form.get('kid')
    sid = request.form.get('sid')
    status = request.form.get('status', '-1')  # 注意 不能转换为int 因为int中0为假
    records = ReService.pages(page=page, year=year, k_id=kid, stu_id=sid, status=status)
    if int(records.get('total')) > 0:
        return jsonify(status=True, result=records)
    return jsonify(status=False, result={})


# 标记请假状态
@record.route("/qingjia/<rid>", methods=['post'])
@ad_login.required
def qingjia(rid):
    if rid and rid > 0:
        if ReService.change(rid, rd_status=Check.QJ):
            return jsonify(status=True)
    return jsonify(status=False, msg="无法标记请假")


# 数据execl导出
@record.route('/export')
@ad_login.required
def export_1():
    year = request.args.get('year', '2018')
    kid  = int(request.args.get('kid', '0'))
    sid  = int(request.args.get('sid', '0'))
    status = request.args.get('status', '-1')
    page = ReService.pages(1, 200000000, year=year, k_id=kid, stu_id=sid, status=status)
    filename = getRecordExecl(page.get("result"))
    return send_file(filename, as_attachment=True, attachment_filename='签到记录.xls')


def render(view, data=None):
    u_id = u_login.get_user_id()
    stu = StuService.find_by_id(u_id)
    if stu:
        return render_template(view, username=stu.stu_name, stu=stu, data=data)
    return render_template("error/404.html")
